<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="utf-8">
    <title>用户列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" th:href="@{/static/plugin/layui/css/layui.css}" media="all">
</head>
<body>
<div class="searchTable">
    <div class="layui-inline">
        <input class="layui-input" name="s_realname" id="s_realname" autocomplete="off" placeholder="昵称">
    </div>
    <div class="layui-inline">
        <input class="layui-input" name="s_username" id="s_username" autocomplete="off" placeholder="账号">
    </div>
    <button type="button" id="searchBtn" class="layui-btn" data-type="reload">搜索</button>
</div>

<!--二维列表-->
<table class="layui-hide" id="SysUser" lay-filter="SysUser"></table>

<input type="text" id="ctx" hidden="hidden" th:value="${#request.getContextPath()}">

<!--编辑表单-->
<div class="layui-row" id="editForm" style="display:none;">
    <div class="layui-col-md10">
        <form class="layui-form layui-from-pane" action="" style="margin-top:20px; margin-right: 20px">
            <input type="text" id="id" name="id" hidden="hidden">
            <div class="layui-form-item" >
                <label class="layui-form-label">昵称</label>
                <div class="layui-input-block">
                    <input type="text" id="realname" name="realname" required lay-verify="required" autocomplete="off"
                           placeholder="" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">账号</label>
                <div class="layui-input-block">
                    <input type="text" id="username" name="username" required lay-verify="required" autocomplete="off"
                           placeholder="" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">角色</label>
                <div class="layui-input-block">
                    <select id="roleSelect" name="roleSign" lay-verify="required">

                    </select>
                    <div class="layui-unselect layui-form-select">
                        <div class="layui-select-title">
                            <input type="text" placeholder="请选择" value="" readonly=""
                                   class="layui-input layui-unselect">
                            <i class="layui-edge"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item" style="margin-top:40px">
                <div class="layui-input-block">
                    <button type="button" class="layui-btn  layui-btn-submit " lay-submit="" lay-filter="confirm">保存</button>
                    <button type="button" class="layui-btn layui-btn-primary" id="back">取消</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script type="text/html" id="userToolBar">
    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-sm" lay-event="add" shiro:hasPermission="/account/add">新增</button>
    </div>
</script>

<script type="text/html" id="tbBar">
<!--    &lt;!&ndash;查看账号&ndash;&gt;-->
<!--    <i style="font-size: 24px; color: #4178ff;" class="layui-icon layui-icon-list " lay-event="get"-->
<!--       shiro:hasPermission="/account/get"></i>-->
    <!--编辑账号-->
    <i style="font-size: 24px; color: #298f83;" class="layui-icon layui-icon-edit " lay-event="modify"
       shiro:hasPermission="/account/modify"></i>
    <!--删除账号-->
    <i style="font-size: 24px; color: #f4577b;" class="layui-icon layui-icon-delete " lay-event="remove"
       shiro:hasPermission="/account/delete"></i>
<!--    &lt;!&ndash;重置密码&ndash;&gt;-->
<!--    <i style="font-size: 20px; color: #f1823a;" class="layui-icon layui-icon-password " lay-event="resetPwd"-->
<!--       shiro:hasPermission="/account/resetPwd"></i>-->
</script>

<script th:src="@{/static/js/jquery.min.js}" charset="utf-8"></script>
<script th:src="@{/static/plugin/layui/layui.js}" charset="utf-8"></script>
<script th:src="@{/static/js/app.js}" charset="utf-8"></script>
<script src="/static/js/whysu.js" th:src="@{/static/js/whysu.js}"></script>

<!--序号自增-->
<script type="text/html" id="xuhao">
    {{d.LAY_TABLE_INDEX+1}}
</script>

<script>
    layui.use(['jquery', 'table'], function () {
        var table = layui.table;
        var form = layui.form;

        table.render({
            elem: '#SysUser'
            , url: ctx + '/account/getPage'
            , method: 'post'
            , contentType: 'application/json'
            , toolbar: '#userToolBar' //开启头部工具栏，并为其绑定左侧模板
            , defaultToolbar: false //去掉右上角的打印等按钮
            , title: 'SysUser'
            , loading: true //显示加载条
            , cols: [
                [
                    {title: '序号', templet: '#xuhao', align: 'center'}
                    , {field: 'id', title: 'ID', align: 'center', hide: true}
                    , {field: 'realname', title: '昵称', align: 'center'}
                    , {field: 'username', title: '账号', align: 'center'}
                    , {field: 'roleName', title: '角色', align: 'center'}
                    , {field: 'voucherNameList', title: '所属凭证组', align: 'center'}
                    , {field: 'roleSign', title: '角色标志', align: 'center', hide: true}
                    , {field: 'createUser', title: '创建人', align: 'center', hide: true}
                    , {
                    field: 'createTime', title: '创建时间',
                    templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>'
                }
                    , {
                    field: 'updateTime', title: '更新时间', width: 180, hide: true,
                    templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>'
                }
                    , {
                    field: 'lastLoginTime', title: '最后登录时间',
                    templet: '<div>{{ layui.util.toDateString(d.lastLoginTime, "yyyy-MM-dd HH:mm:ss") }}</div>'
                }
                    , {fixed: 'right', title: '操作', toolbar: '#tbBar'}
                ]
            ]
            , page: true
            , request: {
                pageName: 'pageNum'//页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": 0, //解析接口状态
                    "msg": "", //解析提示文本
                    "count": res.body.totalSize, //解析数据长度
                    "data": res.body.list //解析数据列表
                };
            }

        });

        /*重载*/
        var $ = layui.$, active = {
            reload: function () {
                var queryWhere = {};
                // 账号
                var userName$_ = $('#s_username');
                if (userName$_.val() != '') {
                    queryWhere['username'] = userName$_.val();
                }
                // 昵称
                var realname$_ = $('#s_realname');
                if (realname$_.val() != '') {
                    queryWhere['realname'] = realname$_.val();
                }
                //执行重载
                table.reload('SysUser', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: queryWhere
                    , done: function (res, curr, count) {
                        this.where = {};
                    }
                }, 'data');
            }
        };

        /*搜索*/
        $('#searchBtn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        /*新增、修改账号*/
        form.on('submit(confirm)', function (massage) {
            $.ajax({
                url: ctx + '/account/addOrModify',
                type: "POST",
                contentType: "application/json",
                dataType: "json",
                data: requestDTO(massage.field),
                beforeSend: function () {
                    this.layerIndex = showLoad();
                },
                complete: function () {
                    closeLoad(this.layerIndex);
                },
                success: function (data) {
                    if (data.result.code == 200) {
                        // 关闭所有弹窗
                        layer.closeAll();
                        // 操作成功
                        layer.msg("操作成功", {
                            time: 1000
                        })
                        // 重新加载表格
                        table.reload('SysUser');
                    } else {
                        layer.msg(data.result.message);
                    }
                }
            });

            return false;
        });

        //头工具栏事件
        table.on('toolbar(SysUser)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                //自定义头工具栏右侧图标 - 提示
                case 'add': {
                    var updateIndex = layer.open({
                        //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                        type: 1,
                        title: "新增",
                        area: ['60%', '80%'],
                        content: $("#editForm")//引用的弹出层的页面层的方式加载修改界面表单
                    });
                    setFormValue(null, null);
                    break;
                }
                default:
                    break;
            }
            ;
        });

        //监听弹出框表单提交，massage是修改界面的表单数据'submit(confirm),是修改按钮的绑定

        //监听行工具事件
        table.on('tool(SysUser)', function (obj) {
            var data = obj.data;
            // console.log(obj)
            if (obj.event === 'remove') {
                layer.confirm('确定删除该账号？', function (index) {
                    $.ajax({
                        type: "POST",
                        url: ctx + "/account/delete",
                        contentType: "application/json",
                        dataType: "json",
                        data: requestDTO(data.id),
                        beforeSend: function () {
                            this.layerIndex = showLoad();
                        },
                        complete: function () {
                            closeLoad(this.layerIndex);
                        },
                        success: function (response) {
                            if (response.result.code == 200) {
                                layer.msg("操作成功", {
                                    timeout: 1000
                                }, function () {
                                    // 关闭窗口
                                    layer.close(index);
                                })
                                //执行重载
                                var queryWhere = {};
                                table.reload('SysUser', {
                                    page: {
                                        curr: 1 //重新从第 1 页开始
                                    }
                                    , where: queryWhere
                                    , done: function (res, curr, count) {
                                        this.where = {};
                                    }
                                }, 'data');
                            } else {
                                layer.msg(response.result.message)
                            }
                        },
                        error: function (e) {
                            console.log("ERROR: ", e);
                        }
                    });
                });
            } else if (obj.event === 'modify') {
                //iframe层-父子操作
                var updateIndex = layer.open({
                    //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    type: 1,
                    title: "修改",
                    area: ['60%', '80%'],
                    content: $("#editForm")//引用的弹出层的页面层的方式加载修改界面表单
                });
                setFormValue(obj, data);
            }
        });

        // 填充form
        function setFormValue(obj, data) {
            var target = $("#roleSelect");
            $.ajax({
                type: "GET",
                url: ctx + '/role/getSelectList',
                success: function (res) {
                    target.find("option").remove();
                    target.append(new Option());
                    $.each(res.body, function (index, item) {
                        target.append(new Option(item.roleName, item.roleSign));
                    });
                    if (data != null) {
                        // 选中当前角色
                        target.val(data.roleSign);
                    }
                    layui.form.render("select");
                }
            });
            if (data != null) {
                $("#id").val(data.id);
                $("#username").val(data.username);
                $("#realname").val(data.realname);
            } else {
                $("#id").val('');
                $("#username").val('');
                $("#realname").val('');
            }
            layui.form.render("select");
        }

        $("#back").on('click', function () {
            layer.closeAll();
        });

    });
</script>

</body>
</html>